package com.ethink.gateway.filter.pre;

import cn.hutool.core.util.IdUtil;
import com.ethink.framework.log.constant.LogConstant;
import com.ethink.gateway.constant.GatewayConstant;
import com.ethink.gateway.filter.AbstractPreFilter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

/**
 * 添加全局traceId
 *
 * @author wanghaiyong
 */
@Slf4j
@Component
public class TraceFilter extends AbstractPreFilter {
    @Override
    public int getOrder() {
        return GatewayConstant.FILTER_ORDER_TRACE;
    }


    @Override
    protected ServerWebExchange preFilter(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String traceId = IdUtil.getSnowflakeNextIdStr();
        MDC.put(LogConstant.LOG_TRACE_ID, traceId);
        request.mutate().header(LogConstant.TRACE_ID_HEADER, traceId);
        return exchange.mutate().request(request).build();
    }
}
